package com.hoshiicloud.saleorder.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hoshiicloud.common.aop.Logable;
import com.hoshiicloud.common.exception.CommonError;
import com.hoshiicloud.common.exception.QueryException;
import com.hoshiicloud.common.exception.ServiceException;
import com.hoshiicloud.common.query.OmnipotentWrapper;
import com.hoshiicloud.saleorder.entity.OrderInfo;
import com.hoshiicloud.saleorder.entity.OrderMain;
import com.hoshiicloud.saleorder.feign.IdGeneratorService;
import com.hoshiicloud.saleorder.mapper.OrderInfoMapper;
import com.hoshiicloud.saleorder.service.OrderInfoService;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * <p>
 * 订单信息 服务实现类
 * </p>
 *
 * @author zhangshuhu
 * @since 2019-06-03
 */
@Slf4j
@Service
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements
        OrderInfoService {

    @Autowired
    private IdGeneratorService idGeneratorService;
    private OrderInfo entity;

    @Autowired
    private OrderInfoMapper orderInfoMapper;


    /**
     * @param id
     * @return com.hoshiibuy.saleorder.entity.OrderInfo
     * @description: 根据id查询订单信息
     */
    @Override
    @Cacheable(cacheNames = "OrderInfo", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#id")
    @Logable(authName = "销售订单-订单信息-查询订单信息 ")
    public OrderInfo getById(Long id) {
        return Optional.ofNullable(baseMapper.selectById(id))
                .orElseThrow(() -> new QueryException("无法找到订单信息记录"));
    }

    /**
     * @param entity
     * @return boolean
     * @description: 新增订单信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "OrderInfo", allEntries = true)
    @Logable(authName = "销售订单-订单信息-新增订单信息")
    public boolean save(OrderInfo entity) {
        return Optional.ofNullable(entity).map(orderInfo -> {
            String id = idGeneratorService.queryGeneratorId();
            log.error("{}", id);

            if (StrUtil.isBlank(id)) {
                log.error("id生成异常");
                throw new ServiceException(CommonError.error("网络开小差啦~, 请重新尝试"));
            }

            orderInfo.setId(Long.parseLong(id));
            orderInfo.setCreatedTime(LocalDateTime.now());

            int row = baseMapper.insert(orderInfo);
            if (row <= 0) {
                log.error("新增订单信息失败");
                throw new ServiceException(CommonError.error("新增订单信息失败"));
            }
            return true;
        }).orElseThrow(() -> new ServiceException(CommonError.error("新增订单信息失败，保存对象为空")));

    }

    /**
     * @param entity
     * @return boolean
     * @description: 修改订单信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "OrderInfo", allEntries = true)
    @Logable(authName = "销售订单-订单信息管理-修改订单信息")
    public boolean updateById(OrderInfo entity) {

        this.entity = entity;
        entity.setUpdatedTime(LocalDateTime.now());
        int row = baseMapper.updateById(entity);
        if (row <= 0) {
            throw new ServiceException(CommonError.error("修改订单信息失败"));
        }
        return true;
    }

    /**
     * @param key
     * @return IPage
     * @description: 分页查询订单信息
     */
    @Override
    @Logable(authName = "销售订单-订单信息管理-分页查询订单信息")
    @Cacheable(cacheNames = "OrderInfo", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+T(com.hoshiicloud.common.utils.DigestUtils).md5(#key)")
    public IPage<OrderInfo> page(IPage<OrderInfo> page, Wrapper<OrderInfo> queryWrapper, String key) {

        return baseMapper.selectPage(page, queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "OrderInfo", allEntries = true)
    @Logable(authName = "销售订单-订单信息管理-删除订单信息")
    public boolean deleteById(Long id) {
        OrderInfo entity = this.getById(id);

        return Optional.ofNullable(entity).map(orderInfo -> {
            orderInfo.setUpdatedTime(LocalDateTime.now());
            orderInfo.setDeleted(1);
            int row = baseMapper.updateById(orderInfo);
            if (row <= 0) {
                throw new ServiceException(CommonError.error("删除失败"));
            }
            return true;
        }).orElseThrow(() -> {
            log.error("删除订单信息异常，无法找到订单信息记录");
            return new QueryException("删除订单信息异常, 无法找到订单信息记录");
        });
    }

    @Override
    @Cacheable(cacheNames = "OrderInfo", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#key")
    @Logable(authName = "销售订单-订单信息管理-根据id集合查询订单信息")
    public List<OrderInfo> getByIds(List<Long> ids, String key) {
        return baseMapper.selectBatchIds(ids);
    }

    @Override
    @Cacheable(cacheNames = "OrderInfo", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#orderId")
    public List<OrderInfo> listByOrderId(Long orderId) {
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(true, OrderInfo::getMainId, orderId);
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    @SneakyThrows
    public List<OrderInfo> listByPayOrderId(Long payOrderId) {
        QueryWrapper<OrderInfo> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(true, OrderInfo::getPayOrderId, payOrderId);
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    public List<OrderInfo> listByQueryWrapper(QueryWrapper<OrderInfo> queryWrapper) {
        return baseMapper.selectList(queryWrapper);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(cacheNames = "OrderInfo", allEntries = true)
    @Logable(authName = "销售订单-订单信息管理-批量更新子订单信息")
    public boolean updateByList(List<OrderInfo> orderInfoList) {
        return this.updateBatchById(orderInfoList);
    }

    @Override
    public List<Map<String, Object>> multiConditionBranchOrders(Map<String, Object> branchOrderQueryParam, Page page) {
        return orderInfoMapper.multiConditionBranchOrders(branchOrderQueryParam, page);
    }

    @Override
    public List<Map<String, Object>> multiConditionBranchOrders(Map<String, Object> branchOrderQueryParam) {
        return orderInfoMapper.multiConditionBranchOrders(branchOrderQueryParam);
    }

    @Override
    @Cacheable(cacheNames = "OrderInfo", key = "#root.targetClass.simpleName+':'+#root.methodName+': categoryId('+ #categoryId + ')'")
    public String selectBaseSpuCategoryId(String categoryId) {
        return orderInfoMapper.selectBaseSpuCategoryId(categoryId);
    }

    /**
     * 根据扩展spu主键组查询销售数量
     * @param wrapper 查询条件
     * @return List<Map<String, Object>>
     */
    @Override
    @Logable(authName = "销售订单-订单信息管理-根据扩展spu主键组查询销售数量")
    public List<Map<String, Object>> selectSalesCountBySpuIds(QueryWrapper<OrderInfo> wrapper) {
        return orderInfoMapper.selectSalesCountBySpuIds(wrapper);
    }

    /**
     * 根据总店分组查询已售数量
     * @param wrapper 查询参数
     * @return List<Map<String, Object>>
     */
    @Override
    @Logable(authName = "销售订单-订单信息管理-根据总店分组查询已售数量")
    public List<Map<String, Object>> selectSalesCountGroupByStorePid(QueryWrapper<OrderInfo> wrapper) {
        return orderInfoMapper.selectSalesCountGroupByStorePid(wrapper);
    }

    /**
     * 按店铺分组获取店铺粉丝数和购买指数
     * @param queryWrapper 查询参数
     * @return List<Map<String,Object>>
     */
    @Override
    @Logable(authName = "销售订单-订单信息管理-按店铺分组获取店铺粉丝数和购买指数")
    public List<Map<String, Object>> getStoreFansAndBuyExponentGroupById(QueryWrapper<OrderInfo> queryWrapper) {
        return orderInfoMapper.getStoreFansAndBuyExponentGroupById(queryWrapper);
    }

    @Override
    @Cacheable(cacheNames = "OrderInfo", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#mainId")
    @Logable(authName = "销售订单-订单信息管理-根据主订单ID 获取所有子订单")
    public List<OrderInfo> listByMainId(Long mainId) {
        QueryWrapper<OrderInfo> q = new QueryWrapper<>();
        q.lambda().eq(OrderInfo::getMainId,mainId).eq(OrderInfo::getDeleted,0);
        return orderInfoMapper.selectList(q);
    }

    /**
     * 根据自定义条件查询商品子单信息
     */
    @Override
    @Cacheable(cacheNames = "OrderInfo", key = "#root.targetClass.simpleName+':'+#root.methodName+':'+#key")
    public List<OrderInfo> omniQueryOrderMain(List<OmnipotentWrapper> wrappers, String key) {
        OmnipotentWrapper<OrderInfo> omnipotentWrapper = new OmnipotentWrapper();
        QueryWrapper<OrderInfo> wrapper = omnipotentWrapper.getWrapper(wrappers);
        return baseMapper.selectList(wrapper);
    }
}
